//
//  ZXUIImagePickerManager.m
//  Baby
//
//  Created by simon on 16/4/19.
//  Copyright © 2016年 sina. All rights reserved.
//

#import "ZXUIImagePickerManager.h"
#import <CoreServices/CoreServices.h>
#import <objc/runtime.h>
#import "CAIPhotoAuthorizationManager.h"
#import <UniformTypeIdentifiers/UniformTypeIdentifiers.h>
#import "CAICameraOverlayView.h"
#import "CAIImagePickerKitTool.h"
#import "CAIImageLocationManager.h"
#import <ZXUIImageUtils/ZXUIImageUtils.h>


static char pickerControllerActionKey;

@interface ZXUIImagePickerManager ()<CAICameraOverlayViewDelegate>

/// 设置picker控制器界面要显示的资源类型；
@property (nonatomic, assign) UIImagePickerControllerSourceType sourceType;

@property (nonatomic, strong) UIImagePickerController *imagePicker;

/// 设置媒体选择控制器要访问的媒体类型的数组；默认只支持kUTTypeImage媒体类型；
@property(nonatomic, copy) NSArray <NSString *> *mediaTypes;

/// 最大拍摄数量;自定义相机的时候；
@property (nonatomic, assign) NSInteger maxTakePhotoNum;
@property (nonatomic, assign) BOOL isCustomCamera;


@property (nonatomic, strong) CAICameraOverlayView *cameraOverlayView;
@property (nonatomic, strong) NSDate *startDate;

@end

@implementation ZXUIImagePickerManager

@synthesize cameraOverlayApperance = _cameraOverlayApperance;

- (void)dealloc{
    NSLog(@"被释放了，同时指向它的imagePicker的delegate弱引用被置nil，imagePicker也接着被释放");
}



- (instancetype)init
{
    self = [super init];
    if (self)
    {
        self.allowsEditing = NO;
        self.alwayCheckAuthorization = YES;
        self.videoMaximumDuration = 10 * 60;
        self.videoQuality = UIImagePickerControllerQualityTypeMedium;
        ///kUTTypeImage、kUTTypeMovie、(NSString *)kUTTypeLivePhoto///官方文档不准，目前已支持三种格式
        if (@available(iOS 9.1, *)) {
            self.mediaTypes = @[(NSString *)kUTTypeImage,(NSString *)kUTTypeLivePhoto];
        } else {
            self.mediaTypes = @[(NSString *)kUTTypeImage];
            // Fallback on earlier versions
        }
    }
    return self;
}

#pragma mark - 实例方法

- (void)presentPhotoActionSheetToImagePickerWithSourceController:(UIViewController *)sourceController
{
    NSString *title = [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]?NSLocalizedString(@"选择", nil):nil;
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"取消", nil) style:UIAlertActionStyleCancel handler:nil];
    [alertController addAction:cancelAction];

    __weak __typeof(&*self)weakSelf = self;
    UIAlertAction *cameraAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"拍照", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf presentCameraPhotoWithSourceController:sourceController];
    }];
    [alertController addAction:cameraAction];

    
    UIAlertAction *albumAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"从相册选择", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        [weakSelf presentPhotoLibraryWithSourceController:sourceController];
    }];
    [alertController addAction:albumAction];
    [sourceController presentViewController:alertController animated:YES completion:nil];
}




#pragma mark - 弹出相机

/// 弹出摄像头，相机；只有在sourceType是UIImagePickerControllerSourceTypeCamera时才可以添加camera；不然会崩溃；
/// @param sourceController sourceController description
- (void)presentCameraPhotoWithSourceController:(UIViewController *)sourceController{
    
    [self presentCameraWithSourceController:sourceController allowTakePhoto:YES allowTakeVideo:NO];
}


- (void)presentCameraMovieWithSourceController:(UIViewController *)sourceController{
    
    [self presentCameraWithSourceController:sourceController allowTakePhoto:NO allowTakeVideo:YES];
}


- (void)presentCameraWithSourceController:(UIViewController *)sourceController
                           allowTakePhoto:(BOOL)allowTakePhoto
                           allowTakeVideo:(BOOL)allowTakeVideo{
    self.isCustomCamera = NO;
    __weak __typeof(&*self)weakSelf = self;
    [self checkCameraWithSourceController:sourceController successBlock:^{
        if (allowTakePhoto && !allowTakeVideo) {
            weakSelf.mediaTypes = @[(NSString *) kUTTypeImage];
        }
        else if (!allowTakePhoto && allowTakeVideo){
            weakSelf.mediaTypes = @[(NSString *) kUTTypeMovie];
        }
        else if (allowTakePhoto && allowTakeVideo){
            weakSelf.mediaTypes = @[(NSString *) kUTTypeImage,(NSString *) kUTTypeMovie];
        }
        else{
            NSAssert(allowTakePhoto || allowTakeVideo, @"必须允许拍照或拍视频其一");
        }
        [weakSelf presentCameraControllerWithSourceController:sourceController];
    }];
}

- (void)presentCameraMultiPhotoWithSourceController:(UIViewController *)sourceController
                                    maxTakePhotoNum:(NSInteger)maxTakePhotoNum{
    self.maxTakePhotoNum = maxTakePhotoNum;
    self.isCustomCamera = YES;
    self.allowsEditing = NO;
    __weak __typeof(&*self)weakSelf = self;
    [self checkCameraWithSourceController:sourceController successBlock:^{
        weakSelf.mediaTypes = @[(NSString *) kUTTypeImage];
        [weakSelf presentCameraControllerWithSourceController:sourceController];
    }];
}

#pragma mark-

- (void)checkCameraWithSourceController:(UIViewController *)sourceController successBlock:(void(^)(void))success
{
    ///防止连续调用二次弹出相机崩溃；
    if (self.imagePicker.presentingViewController){
        return;
    }
    // 判断相机资源是否有效：设备不支持
    if(![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
        [self presentGeneralAlertInViewController:sourceController withTitle:@"当前相机不可用" message:nil cancelButtonTitle:nil cancleHandler:nil doButtonTitle:@"确定" doHandler:nil];
        [self respondDelegateErrorWithCode:ImagePickerControllerErrorCodeCameraError];
        return;
    }
    if (![self isAvailableCamera]) {
        NSString *title = self.cameraDevice == UIImagePickerControllerCameraDeviceFront ? @"该设备不支持前置摄像头拍照":@"该设备不支持后置摄像头拍照";
        [self presentGeneralAlertInViewController:sourceController withTitle:title message:nil cancelButtonTitle:nil cancleHandler:nil doButtonTitle:@"确定" doHandler:nil];
        [self respondDelegateErrorWithCode:ImagePickerControllerErrorCodeCameraError];
        return;
    }
    self.sourceType = UIImagePickerControllerSourceTypeCamera;
    if (self.alwayCheckAuthorization)
    {
        __weak __typeof(&*self)weakSelf = self;
        [[CAIPhotoAuthorizationManager shareInstance] requestCameraAuthorizationWithDeniedAlertViewInViewController:sourceController call:^(ZXPhotoAuthorizationStatus status) {
            if (status == ZXPhotoAuthorizationStatusAuthorized)
            {
                if (success) {
                    success();
                }
            }else{
                [weakSelf respondDelegateErrorWithCode:ImagePickerControllerErrorCodeNOCameraAuthorization];
            }
            return;
        }];
    }
    else
    {
        if (success) {
            success();
        }
    }
}

/// 弹出UIImagePickerController 摄像头模式方法
/// 当图像选取器的源类型被设置为UIImagePickerControllerSourceTypeCamera以外的值时调用camera有关属性，会抛出一个NSInvalidArgumentException异常。
- (void)presentCameraControllerWithSourceController:(UIViewController *)sourceController{
    
    if (self.sourceType != UIImagePickerControllerSourceTypeCamera || self.mediaTypes.count==0) {
        return;
    }
    self.imagePicker.sourceType = self.sourceType;
    self.imagePicker.mediaTypes = self.mediaTypes;
    if (self.imagePicker.mediaTypes.count == 1 && [[self.imagePicker.mediaTypes firstObject] isEqualToString:(NSString *) kUTTypeMovie]) {
        self.imagePicker.cameraCaptureMode = UIImagePickerControllerCameraCaptureModeVideo;
    }
    else if (self.imagePicker.mediaTypes.count == 1 && [[self.imagePicker.mediaTypes firstObject] isEqualToString:(NSString *) kUTTypeImage]) {
        self.imagePicker.cameraCaptureMode = UIImagePickerControllerCameraCaptureModePhoto;
    }
    //  当同时支持照片和视频的时候，这个就是优先展示的模式；
    else{
        self.imagePicker.cameraCaptureMode = UIImagePickerControllerCameraCaptureModePhoto;
    }
    self.imagePicker.allowsEditing = self.allowsEditing;
    self.imagePicker.cameraDevice = self.cameraDevice;
    if ([self.imagePicker.mediaTypes containsObject:(NSString *) kUTTypeMovie]) {
        self.imagePicker.videoMaximumDuration = self.videoMaximumDuration;
        self.imagePicker.videoQuality = self.videoQuality;
    }
    self.imagePicker.cameraFlashMode = UIImagePickerControllerCameraFlashModeAuto;
    if (self.isCustomCamera) {
        self.imagePicker.showsCameraControls = NO;
        self.cameraOverlayView.maxItemCount = self.maxTakePhotoNum;
        if (self.cameraOverlayApperance) {
            self.cameraOverlayView.commonTintColor = self.cameraOverlayApperance.tintColor;
        }
        self.imagePicker.cameraOverlayView = self.cameraOverlayView;

    }else{
        self.imagePicker.showsCameraControls = YES;
        self.imagePicker.cameraOverlayView = nil;
    }
    //  2021/11/09 警告  [Camera] Failed to read exposureBiasesByMode dictionary: Error Domain=NSCocoaErrorDomain Code=4864 "*** -[NSKeyedUnarchiver _initForReadingFromData:error:throwLegacyExceptions:]: data is NULL" UserInfo={NSDebugDescription=*** -[NSKeyedUnarchiver _initForReadingFromData:error:throwLegacyExceptions:]: data is NULL}
    [sourceController presentViewController:self.imagePicker animated:YES completion:^{
//        [self.imagePicker.view snapshotViewAfterScreenUpdates:YES];
    }];
}





#pragma mark-弹出相册
/// 弹出相册
/// @param sourceController sourceController description
- (void)presentPhotoLibraryWithSourceController:(UIViewController *)sourceController
{
    ///防止连续调用二次弹出相册崩溃；
    if (self.imagePicker.presentingViewController){
        return;
    }
    self.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    if (@available(iOS 9.1, *)) {
        self.mediaTypes = @[(NSString *)kUTTypeImage,(NSString *)kUTTypeLivePhoto];
    } else {
        self.mediaTypes = @[(NSString *)kUTTypeImage];
        // Fallback on earlier versions
    }
    if (self.alwayCheckAuthorization)
    {
        if (@available(iOS 11, *)) {
            [self presentPhotoPickerWithSourceController:sourceController];
        } else {
            __weak __typeof(&*self)weakSelf = self;
            [[CAIPhotoAuthorizationManager shareInstance] requestPhotoLibraryAuthorizationWithDeniedAlertViewInViewController:sourceController call:^(ZXPhotoAuthorizationStatus status) {

                if (status == ZXPhotoAuthorizationStatusAuthorized)
                {
                    [weakSelf presentPhotoPickerWithSourceController:sourceController];
                }
                else{
                    [weakSelf respondDelegateErrorWithCode:ImagePickerControllerErrorCodeNOPhotoLibraryAuthorization];
                }
            }];
        }
    }
    else
    {
        [self presentPhotoPickerWithSourceController:sourceController];
    }
}


/// 弹出UIImagePickerController相册方法
- (void)presentPhotoPickerWithSourceController:(UIViewController *)sourceController
{
    ///没有经过验证？
    if (self.sourceType == UIImagePickerControllerSourceTypePhotoLibrary || self.sourceType == UIImagePickerControllerSourceTypeSavedPhotosAlbum) {
        if(![UIImagePickerController isSourceTypeAvailable:self.sourceType])
        {
            __weak __typeof(&*self)weakSelf = self;
            [self presentGeneralAlertInViewController:sourceController withTitle:@"还没有照片,马上去拍照一个吧" message:nil cancelButtonTitle:nil cancleHandler:nil doButtonTitle:@"确定" doHandler:^(UIAlertAction *action) {
                [weakSelf presentCameraPhotoWithSourceController:sourceController];
            }];
            return;
        }
    }
    self.imagePicker.mediaTypes = self.mediaTypes;
    self.imagePicker.allowsEditing = self.allowsEditing;
    self.imagePicker.sourceType = self.sourceType;
    [sourceController presentViewController:self.imagePicker animated:YES completion:^{}];
}



#pragma mark - UINavigationControllerDelegate


- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    if (self.sourceType == UIImagePickerControllerSourceTypeCamera) {
        return;
    }
    navigationController.navigationBar.barTintColor = [UIColor whiteColor];
    UIFont *tiFont = [UIFont systemFontOfSize:17];
    UIColor *color = [UIColor blackColor];
    [navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:color,NSFontAttributeName:tiFont}];
}


#pragma mark - imagePickerControllerDelegate

// 如果想之后立刻调用UIVideoEditor,animated不能是YES。最好的还是dismiss结束后在调用editor。不懂？
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:^{
        
    }];
    self.imagePicker = nil;
    if (self.isCustomCamera) {
        self.cameraOverlayView = nil;
    }
    [self respondDelegateErrorWithCode:ImagePickerControllerErrorCodeCancel];
}

///假如拍照的照片image.imageOrientation:UIImageOrientationRight；上传到其它系统显示会有问题；
///使用编辑属性后，UIImagePickerControllerEditedImage，方向始终变为UIImageOrientationUp；上传到其它系统显示不会有问题；
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    NSString *mediaType =[info objectForKey:UIImagePickerControllerMediaType];
    //如果返回回来的是照片\实况照片
    if (@available(iOS 9.1, *)) {
        ///拍照不返回，只有选择照片时会返回。选择照片：非编辑模式返回，编辑模式不反回；如果是编辑模式，则返回的肯定是public.image;
        if ([mediaType isEqualToString:(NSString *)kUTTypeLivePhoto])
        {
            PHLivePhoto *livePhoto = [info objectForKey:UIImagePickerControllerLivePhoto];
            [self pickingSingleImageWithPicker:picker imageInfo:info livePhoto:livePhoto];
            return;
        }
    }
    if ([mediaType isEqualToString:(NSString *)kUTTypeImage])
    {
        if (self.isCustomCamera) {
            [self takeMultiPhotoWithPicker:picker imageInfo:info livePhoto:nil];
        }else{
            [self pickingSingleImageWithPicker:picker imageInfo:info livePhoto:nil];
        }
    }
    else if ([mediaType isEqualToString:(NSString *)kUTTypeMovie])
    {
        if (picker.sourceType == UIImagePickerControllerSourceTypeCamera && self.allowWriteToSavedPhotos)
        {
            NSURL *url = [info objectForKey:UIImagePickerControllerMediaURL];
            NSString *path =url.path;
            UISaveVideoAtPathToSavedPhotosAlbum(path, self, @selector(video:didFinishSavingWithError:contextInfo:), nil);
        }
        [picker dismissViewControllerAnimated:YES completion:nil];
        self.imagePicker = nil;
    }
}



- (void)pickingSingleImageWithPicker:(UIImagePickerController *)picker imageInfo:(NSDictionary *)info livePhoto:(id)livePhoto{
    
    UIImage *image = nil;
    UIImage *originalImage = [info objectForKey:UIImagePickerControllerOriginalImage];
    if (picker.allowsEditing){
        image = [info objectForKey:UIImagePickerControllerEditedImage];
    }else{
        image = originalImage;
    }
    //解决在拍照后出现异常，回调image是nil的处理；系统偶现的异常特殊处理。
    if (!image) {
        [self respondDelegateErrorWithCode:ImagePickerControllerErrorCodeCameraError];
        [picker dismissViewControllerAnimated:YES completion:nil];
        self.imagePicker = nil;
        return;
    }
    //如果是camera的照片,save original photos到photosAlbum
    if (image && picker.sourceType == UIImagePickerControllerSourceTypeCamera && self.allowWriteToSavedPhotos)
    {
//             //第一次会触发存照片权限提示，如果不允许，则以后不会再提示；plist必须加入存照片的权限key，否则会崩溃；
        dispatch_async(dispatch_get_main_queue(), ^{
            UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
        });
    }
    UIImage *fixImage = [CAIImagePickerKitTool fixOrientation:image];
    if (@available(iOS 9.1, *)) {
        if ([self.delegate respondsToSelector:@selector(imagePickerControllerManager:didFinishPickingLivePhoto:image:error:)] && livePhoto) {
            [self.delegate imagePickerControllerManager:self didFinishPickingLivePhoto:livePhoto image:fixImage error:nil];
            [picker dismissViewControllerAnimated:YES completion:nil];
            self.imagePicker = nil;
            return;
        }
    } else {
        // Fallback on earlier versions
    }
    if ([self.delegate respondsToSelector:@selector(imagePickerControllerManager:didFinishPickingImages:imageModels:error:)]) {
        [self.delegate imagePickerControllerManager:self didFinishPickingImages:@[fixImage] imageModels:nil error:nil];
    }
    else if ([self.delegate respondsToSelector:@selector(imagePickerControllerManager:didFinishPickingImageWithInfo:image:error:)]) {
        [self.delegate imagePickerControllerManager:self didFinishPickingImageWithInfo:info image:fixImage error:nil];
    }
    else if ([self.delegate respondsToSelector:@selector(imagePickerControllerManager:imagePickerController:didFinishPickingMediaWithInfo:image:error:)]) {
        [self.delegate imagePickerControllerManager:self imagePickerController:picker didFinishPickingMediaWithInfo:info image:fixImage error:nil];
    }
    [picker dismissViewControllerAnimated:YES completion:nil];
    self.imagePicker = nil;
}


- (void)takeMultiPhotoWithPicker:(UIImagePickerController *)picker imageInfo:(NSDictionary *)info livePhoto:(id)livePhoto{
    
#if DEBUG
    NSTimeInterval interval = -[self.startDate timeIntervalSinceNow];
    NSLog(@"%f",interval);
#else
#endif
    
    UIImage *image = nil;
    UIImage *originalImage = [info objectForKey:UIImagePickerControllerOriginalImage];
    if (picker.allowsEditing){
        /// 自定义相机不支持编辑模式；
        UIImage *editImage = [info objectForKey:UIImagePickerControllerEditedImage];
        image = editImage ? editImage :originalImage;
    }else{
        image = originalImage;
    }
    //解决在拍照后出现异常，回调image是nil的处理；系统偶现的异常特殊处理。
    if (!image) {
        [self respondDelegateErrorWithCode:ImagePickerControllerErrorCodeCameraError];
        [picker dismissViewControllerAnimated:YES completion:nil];
        self.imagePicker = nil;
        self.cameraOverlayView = nil;
        return;
    }
//    UIImage *fixImage = [CAIImagePickerKitTool fixOrientation:image];
    if (image && self.imagePicker && picker.sourceType == UIImagePickerControllerSourceTypeCamera && self.allowWriteToSavedPhotos)
    {
       //第一次会触发存照片权限提示，如果不允许，则以后不会再提示；plist必须加入存照片的权限key，否则会崩溃；
        dispatch_async(dispatch_get_main_queue(), ^{
            UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
        });
    }
    if (self.watermask) {
        if ([self.delegate respondsToSelector:@selector(cameraWatermaskImage:cameraImage:)]) {
            UIImage *watermask = [self.delegate cameraWatermaskImage:self cameraImage:image];
            image = watermask;
            if (!image) {
                image = [self watermaskImage:image];
            }
        }else{
            image = [self watermaskImage:image];
        }
    }
    CAICameraPhotoInfoModel *photoModel = [CAICameraPhotoInfoModel new];
    photoModel.photo = image;
    photoModel.dateTime = [CAIImagePickerKitTool localizedString2FromDate:[NSDate date] dateFormat:@"yyyy-MM-dd HH:mm:ss"];
    photoModel.location = [CAIImageLocationManager shareInstance].location;
    photoModel.photoId = [[NSUUID UUID] UUIDString];
    [self.cameraOverlayView reloadUIWithTakePicture:photoModel];
}


- (UIImage *)watermaskImage:(UIImage *)image{
    CGFloat scale = image.size.width/[UIScreen mainScreen].bounds.size.width;
    
    WatermaskTextModel *hhmm = [WatermaskTextModel new];
    hhmm.text = [CAIImagePickerKitTool localizedString2FromDate:[NSDate date] dateFormat:@"HH:mm"];
    hhmm.attributes = @{NSFontAttributeName:[UIFont systemFontOfSize:LCDScale_iPhone6(34)*scale weight:UIFontWeightMedium],NSForegroundColorAttributeName:[UIColor whiteColor]};
    hhmm.boundingRect = CGRectMake(LCDScale_iPhone6(12)*scale, (image.size.height-LCDScale_iPhone6(56+41.5)*scale), 0, 0);

    
    WatermaskImageModel *line = [[WatermaskImageModel alloc] init];
    UIImage *maskImage = [UIImage zx_imageWithColor:[UIColor colorWithRed:49.0/255 green:125.0/255 blue:243.0/255 alpha:1] andSize:CGSizeMake(LCDScale_iPhone6(2)*scale, LCDScale_iPhone6(31)*scale)];
    line.maskImage = maskImage;
    line.boundingRect = CGRectMake(LCDScale_iPhone6(102)*scale, (CGRectGetMidY(hhmm.boundingRect)+LCDScale_iPhone6(5)*scale), 0, 0);
    
    WatermaskTextModel *yyyymmdd = [WatermaskTextModel new];
    yyyymmdd.text = [CAIImagePickerKitTool localizedString2FromDate:[NSDate date] dateFormat:@"yyyy-MM-dd"];
    yyyymmdd.attributes = @{NSFontAttributeName:[UIFont systemFontOfSize:LCDScale_iPhone6(14)*scale weight:UIFontWeightMedium],NSForegroundColorAttributeName:[UIColor whiteColor]};
    yyyymmdd.boundingRect = CGRectMake(LCDScale_iPhone6(113)*scale, (CGRectGetMidY(hhmm.boundingRect)+LCDScale_iPhone6(1)*scale),0, 0);

    WatermaskTextModel *EEEE = [WatermaskTextModel new];
    EEEE.text = [CAIImagePickerKitTool localizedString2FromDate:[NSDate date] dateFormat:@"EEEE"];
    EEEE.attributes = @{NSFontAttributeName:[UIFont systemFontOfSize:LCDScale_iPhone6(12)*scale weight:UIFontWeightMedium],NSForegroundColorAttributeName:[UIColor whiteColor]};
    EEEE.boundingRect = CGRectMake(LCDScale_iPhone6(113)*scale, (CGRectGetMinY(yyyymmdd.boundingRect)+LCDScale_iPhone6(21)*scale),0, 0);

    
    WatermaskTextModel *location = [WatermaskTextModel new];
    location.text = [CAIImageLocationManager shareInstance].location;
    location.attributes = @{NSFontAttributeName:[UIFont systemFontOfSize:LCDScale_iPhone6(14)*scale weight:UIFontWeightMedium],NSForegroundColorAttributeName:[UIColor whiteColor]};
    location.boundingRect = CGRectMake(LCDScale_iPhone6(12)*scale, (image.size.height-LCDScale_iPhone6(53)*scale), LCDScale_iPhone6(350)*scale, LCDScale_iPhone6(40)*scale);
    
    image = [UIImage watermarkImageWithBaseDrawing:image watermaskElements:@[hhmm,line,yyyymmdd,EEEE,location]];
    return image;
}

#pragma mark - CAICameraOverlayViewDelegate

- (void)cameraOverlayViewDidCancel:(CAICameraOverlayView *)view{
    [self imagePickerControllerDidCancel:self.imagePicker];
}

- (void)cameraOverlayViewDidTake:(CAICameraOverlayView *)view{
    if (self.imagePicker.sourceType != UIImagePickerControllerSourceTypeCamera || self.imagePicker.showsCameraControls == YES) {
        return;
    }
    if (self.imagePicker.cameraCaptureMode == UIImagePickerControllerCameraCaptureModePhoto) {
#if DEBUG
    self.startDate = [NSDate date];
#else
#endif
        [self.imagePicker takePicture];
    }
}

- (void)cameraOverlayView:(CAICameraOverlayView *)view
   didFinishPickingImages:(NSArray<UIImage *> *)images
              imageModels:(nonnull NSArray<CAIUIImagePickerCameraPhotoModel *> *)models{
//    NSLog(@"%f", CACurrentMediaTime());
    if ([self.delegate respondsToSelector:@selector(imagePickerControllerManager:didFinishPickingImages:imageModels:error:)]) {
//        NSMutableArray *fixImageMArray = [NSMutableArray array];
//        [images enumerateObjectsUsingBlock:^(UIImage * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
//            UIImage *fixImage = [CAIImagePickerKitTool fixOrientation:obj];
//            [fixImageMArray addObject:fixImage];
//        }];
        [self.delegate imagePickerControllerManager:self didFinishPickingImages:images imageModels:models error:nil];
    }
//    __weak __typeof(&*self)weakSelf = self;
//    [self.imagePicker dismissViewControllerAnimated:YES completion:^{
//        weakSelf.imagePicker = nil;
//        weakSelf.cameraOverlayView = nil;
//    }];
}

- (void)cameraOverlayViewDidTakeLimitNumberNotAllow:(CAICameraOverlayView *)view{
    if ([self.delegate respondsToSelector:@selector(cameraMultiPhotoDidTakeLimitNumberNotAllow:)]) {
        [self.delegate cameraMultiPhotoDidTakeLimitNumberNotAllow:self];
    }
}

#pragma mark - 其它方法

- (void)dismissCamera{
    __weak __typeof(&*self)weakSelf = self;
    [self.imagePicker dismissViewControllerAnimated:YES completion:^{
        ///一定要清除
        weakSelf.cameraOverlayView = nil;
    }];
}

/// 回调error信息通知到代理方法
- (void)respondDelegateErrorWithCode:(ImagePickerControllerErrorCode)code
{
    NSError *error = [CAIImagePickerManagerErrorConst errorWithCode:code];
    ///拍摄多张照片的时候会使用这个
    if ([self.delegate respondsToSelector:@selector(imagePickerControllerManager:didFinishPickingImages:imageModels:error:)]) {
        [self.delegate imagePickerControllerManager:self didFinishPickingImages:nil imageModels:nil error:error];
    }
    else if ([self.delegate respondsToSelector:@selector(imagePickerControllerManager:didFinishPickingImageWithInfo:image:error:)]) {
        [self.delegate imagePickerControllerManager:self didFinishPickingImageWithInfo:nil image:nil error:error];
    }
    else if ([self.delegate respondsToSelector:@selector(imagePickerControllerManager:imagePickerController:didFinishPickingMediaWithInfo:image:error:)]) {
        [self.delegate imagePickerControllerManager:self imagePickerController:self.imagePicker didFinishPickingMediaWithInfo:nil image:nil error:error];
    }
}


// 前面的摄像头是否可用-如果是坏了不知道能不能判断；
- (BOOL) isAvailableFrontCamera{
    BOOL isAvailable = [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront];
    return isAvailable;
}

// 后面的摄像头是否可用-如果是坏了不知道能不能判断；
- (BOOL) isAvailableRearCamera{
    BOOL isAvailable = [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear];
    return isAvailable;
}


- (BOOL) isAvailableCamera{
    if (self.cameraDevice == UIImagePickerControllerCameraDeviceRear && ![self isAvailableRearCamera]) {
        return NO;
    }
    if (self.cameraDevice == UIImagePickerControllerCameraDeviceFront && ![self isAvailableFrontCamera]) {
        return NO;
    }
    return YES;
}



#pragma mark - Setter/Getter

- (UIImagePickerController *)imagePicker{
    if (!_imagePicker) {
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
        imagePicker.delegate = self;
        imagePicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
//        imagePicker.modalPresentationStyle = UIModalPresentationFullScreen;
        _imagePicker = imagePicker;
    }
    return _imagePicker;
}

- (CAICameraOverlayView *)cameraOverlayView{
    if (!_cameraOverlayView) {
        CAICameraOverlayView *view = [[CAICameraOverlayView alloc] init];
        view.delegate = self;
        _cameraOverlayView = view;
    }
    return _cameraOverlayView;
}


#pragma mark -Setter


- (void)setDelegate:(id<ZXUIImagePickerManagerDelegate>)delegate
{
    [self willChangeValueForKey:@"key"];
    objc_setAssociatedObject(self, &pickerControllerActionKey, delegate, OBJC_ASSOCIATION_ASSIGN);
    [self didChangeValueForKey:@"key"];
}



- (id<ZXUIImagePickerManagerDelegate>)delegate
{
    return objc_getAssociatedObject(self, &pickerControllerActionKey);
}


#pragma mark- UIAlertController弹框

- (void)presentGeneralAlertInViewController:(UIViewController *)viewController
                                  withTitle:(nullable NSString *)title
                                    message:(nullable NSString *)message
                          cancelButtonTitle:(nullable NSString *)cancelButtonTitle cancleHandler:(void (^ __nullable)(UIAlertAction *action))handler
                              doButtonTitle:(nullable NSString *)doButtonTitle
                                  doHandler:(void (^ __nullable)(UIAlertAction *action))doHandler
{
    if (!title && message) {
        title = @"";
    }
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    if (cancelButtonTitle.length >0)
    {
        //UIAlertAction的title参数不能为nil，会奔溃；
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(cancelButtonTitle, @"Cancel") style:UIAlertActionStyleCancel handler:handler];
        [alertController addAction:cancelAction];
    }
    if (doButtonTitle.length>0)
    {
        UIAlertAction *doAction = [UIAlertAction actionWithTitle:NSLocalizedString(doButtonTitle, @"OK") style:UIAlertActionStyleDefault handler:doHandler];
        [alertController addAction:doAction];
    }
    [viewController presentViewController:alertController animated:YES completion:nil];
}



#pragma mark - 存储
//始终在主线程执行，自己IMP实现;
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(id)info
{
    NSLog(@"D＝%@,%@",[NSThread currentThread], [NSThread currentThread].name);
    if(error)
    {
        NSLog(@"imageSaveFailed:%@",error.localizedDescription);
    }
    else
    {
        NSLog(@"imageSaveSuccess");
    }
}


- (void)video:(NSString *)videoPath didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    if(error)
    {
        NSLog(@"savefailed:%@",error.localizedDescription);
    }
    else
    {
        NSLog(@"savesuccess");
    }
    NSLog(@"%@",videoPath);
}

@end

/*
 打开闪光灯，然后拍照，拍照的时候同时锁屏。 解锁屏幕后看到相机已经进入预览界面，不过界面是完全的黑色:
 报错如下：
 2020-08-27 15:48:07.533159+0800 菜划算销售端[348:7413] [hcln] HapticClient.mm:352:-[HapticClient finish:]: Player was not running - bailing with error Error Domain=com.apple.CoreHaptics Code=-4805 "(null)" for client 0x100015c
 2020-08-27 15:48:07.534625+0800 菜划算销售端[348:7413] [Feedback] core haptics engine finished for <_UIFeedbackCoreHapticsIgnoreCaptureHapticsOnlyEngine: 0x2838d6060> with error: Error Domain=com.apple.CoreHaptics Code=-4805 "(null)"
 2020-08-27 15:48:08.020081+0800 菜划算销售端[348:8710] [Camera] Attempting to generate BGRA thumbnail data of format 5003 with an invalid surface.
 */


//
//拍照存储的照片：
//jpeg == 5.948195 MB,png == 20.700935 MB, image == <UIImage:0x282c63b10 anonymous {3024, 4032}> ,imageOrientation=3
//横向：jpeg == 4.671441 MB,png == 12.607887 MB, image == <UIImage:0x282c6cea0 anonymous {4032, 3024}> ,imageOrientation=0

//网络图片：
//jpeg == 2.469869 MB,png == 11.081782 MB, image == <UIImage:0x282c60990 anonymous {2600, 3900}> ,imageOrientation=0

//截屏照片：
//jpeg == 0.407666 MB,png == 0.493250 MB, image == <UIImage:0x282c7d050 anonymous {750, 1334}> ,imageOrientation=0

//拍照：
//jpeg == 4.699715 MB,png == 16.767288 MB, image == <UIImage:0x282c786c0 anonymous {3024, 4032}> ,imageOrientation=3
